<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="实验设计" prop="designId">
        <el-select v-model="queryParams.designId" placeholder="请选择实验设计">
            <el-option
              v-for="dict in designList"
              :key="dict.designId"
              :label="dict.designName"
              :value="parseInt(dict.designId)"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="动物编号" prop="animalNumber">
        <el-input
          v-model="queryParams.animalNumber"
          placeholder="请输入动物编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="动物种类" prop="speciesId">
          <el-select v-model="queryParams.speciesId" placeholder="请选择动物种类" clearable >
            <el-option
              v-for="item in speciesList"
              :key="item.speciesId"
              :label="item.speciesName"
              :value="item.speciesId"
            ></el-option>
          </el-select>
        </el-form-item>
      <el-form-item label="健康状态" prop="healthStatus">
        <el-select v-model="queryParams.healthStatus" placeholder="请选择健康状态" clearable>
          <el-option
            v-for="dict in dict.type.animal_health_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['animal:information:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['animal:information:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['animal:information:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['animal:information:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="informationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="实验设计" align="center" prop="designName" />
      <el-table-column label="动物编号" align="center" prop="animalNumber" />
      <el-table-column label="动物种类" align="center" prop="speciesName" />
      <el-table-column label="动物品种" align="center" prop="breedName" />
      <el-table-column label="动物年龄" align="center" prop="age" >
        <template slot-scope="scope">
          <span>{{ scope.row.age }}月</span>
        </template>
      </el-table-column>
      <el-table-column label="健康状态" align="center" prop="healthStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.animal_health_status" :value="scope.row.healthStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="健康检查日期" align="center" prop="lastCheckupDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastCheckupDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="动物图片" align="center" prop="animalImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.animalImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['animal:information:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['animal:information:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleHistory(scope.row)"
          >历史记录</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-picture-outline"
            @click="checkImage(scope.row)"
          >图片校验</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改动物信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="实验设计" prop="designId">
          <!-- <el-input v-model="form.designId" placeholder="请输入实验设计ID" /> -->
          <el-select v-model="form.designId" placeholder="请选择实验设计" >
            <el-option
              v-for="dict in designList"
              :key="dict.designId"
              :label="dict.designName"
              :value="parseInt(dict.designId)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="动物编号" prop="animalNumber">
          <el-input v-model="form.animalNumber" placeholder="请输入动物编号" />
        </el-form-item>
        <!-- <el-form-item label="动物品种" prop="speciesId">
          <el-select v-model="form.speciesId" placeholder="请选择动物品种" clearable>
            <el-option
              v-for="item in speciesList"
              :key="item.speciesId"
              :label="item.speciesName"
              :value="item.speciesId"
            ></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="动物种类" prop="speciesId">
          <el-select v-model="form.speciesId" placeholder="请选择动物种类" clearable @change="getBreedList">
            <el-option
              v-for="item in speciesList"
              :key="item.speciesId"
              :label="item.speciesName"
              :value="item.speciesId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="动物品种" prop="breed">
          <el-select v-model="form.breed" placeholder="请选择动物品种" clearable >
            <el-option
              v-for="item in breedList"
              :key="item.speciesId"
              :label="item.speciesName"
              :value="item.speciesId"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="动物品种" prop="breed">
          <el-input v-model="form.breed" placeholder="请输入动物品种" />
        </el-form-item> -->
        <el-form-item label="动物年龄(月)" prop="age" label-width="100px">
          <el-input v-model="form.age" placeholder="请输入动物年龄" />
        </el-form-item>
        <el-form-item label="健康状态" prop="healthStatus">
          <el-select v-model="form.healthStatus" placeholder="请选择健康状态">
            <el-option
              v-for="dict in dict.type.animal_health_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="健康检查日期" prop="lastCheckupDate" label-width="100px">
          <el-date-picker clearable
            v-model="form.lastCheckupDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择最后健康检查日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="动物图片" prop="animalImage">
          <ImageUpload v-model="form.animalImage" @md5-success="handleMd5Success" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 历史记录对话框 -->
    <el-dialog title="历史记录" :visible.sync="historyOpen" width="1000px" append-to-body>
      <el-table v-loading="loading" :data="historyList"
        border
        fit
        highlight-current-row
        style="width: 100%"
        height="400px"
      >
      <el-table-column label="操作" align="center" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="restoreRow(scope.row)">还原</el-button>
        </template>
      </el-table-column>
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column label="实验设计" align="center" prop="designName" width="150"/>
        <el-table-column label="数据状态" align="center" prop="operationType" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.operationType === 'add'">添加</span>
            <span v-else-if="scope.row.operationType === 'update'">修改</span>
            <span v-else-if="scope.row.operationType === 'delete'">删除</span>
          </template>
        </el-table-column>
        <el-table-column label="动物编号" align="center" prop="animalNumber" width="100" />
    <el-table-column label="动物种类" align="center" prop="speciesName" width="120" />
    <el-table-column label="动物品种" align="center" prop="breedName" width="120" />
    <el-table-column label="动物年龄" align="center" prop="age" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.age }}月</span>
        </template>
      </el-table-column>
      <el-table-column label="健康状态" align="center" prop="healthStatus" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.animal_health_status" :value="scope.row.healthStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="健康检查日期" align="center" prop="lastCheckupDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastCheckupDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="动物图片" align="center" prop="animalImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.animalImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" width="120"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}:{h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updateBy" width="120"/>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}:{h}:{i}') }}</span>
        </template>
      </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listInformation, getInformation, delInformation, addInformation, updateInformation,restoreData,checkImage } from "@/api/animal/information";
import { listSpecies } from "@/api/animal/species";
import { listDesign} from "@/api/experiment/design";
import { getHistoryByAnimalId } from "@/api/animal/history/informationHistory";

export default {
  name: "Information",
  dicts: ['animal_health_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 动物信息表格数据
      informationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //显示历史记录
      historyOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        designId: null,
        animalNumber: null,
        speciesId: null,
        breed: null,
        healthStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        designId: [
          { required: true, message: "实验设计ID不能为空", trigger: "blur" }
        ],
        animalNumber: [
          { required: true, message: "动物编号不能为空", trigger: "blur" }
        ],
        speciesId: [
          { required: true, message: "动物种类不能为空", trigger: "blur" }
        ],
        breed: [
          { required: true, message: "动物品种不能为空", trigger: "blur" }
        ],
      },
      speciesList: [],
      breedList: [],
      designList: [],
      historyList: [],
    };
  },
  created() {
    this.getList();
    this.getSpeciesList();
    this.getDesignList();
  },
  watch: {
    'form.speciesId': function(newVal) {
      if (newVal) {
        this.getBreedList(newVal);
      } else {
        this.breedList = []; // 如果 speciesId 为空，清空 breedList
      }
    }
  },
  methods: {
    /** 查询动物信息列表 */
    getList() {
      this.loading = true;
      listInformation(this.queryParams).then(response => {
        this.informationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        animalId: null,
        designId: null,
        animalNumber: null,
        speciesId: null,
        breed: null,
        age: null,
        healthStatus: null,
        lastCheckupDate: null,
        animalImage: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        deleteBy: null,
        deleteTime: null,
        delFlag: null,
        version: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.animalId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加动物信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const animalId = row.animalId || this.ids
      getInformation(animalId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改动物信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.animalId != null) {
            updateInformation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInformation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const animalIds = row.animalId || this.ids;
      this.$modal.confirm('是否确认删除动物信息编号为"' + animalIds + '"的数据项？').then(function() {
        return delInformation(animalIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('animal/information/export', {
        ...this.queryParams
      }, `information_${new Date().getTime()}.xlsx`)
    },
    /** 获取动物种类下拉列表 */
    getSpeciesList() {
      listSpecies({pageNum: 1000,pageSize: 10}).then(response => {
        this.speciesList = response.data.filter(item => item.parentId === 0);
      });
    },
    getBreedList(speciesId) {
    listSpecies({parentId: speciesId }).then(response => {
      this.breedList = response.data;
    }).catch(error => {
      console.error('获取动物品种列表失败:', error);
    });
  },
    // 获取实验设计数据
    getDesignList() {
      listDesign({pageNum: 1000,pageSize: 10}).then(response => {
        this.designList = response.rows;
      });
    },
//获取历史记录
    handleHistory(row) {
    const animalId = row.animalId;
    getHistoryByAnimalId(animalId).then(response => {
      // 处理返回的历史记录数据
      this.historyList = response.data;
      this.historyOpen = true;
      console.log(response);
      // 你可以在这里打开一个对话框或新页面来显示历史记录
    }).catch(error => {
      console.error("获取历史记录失败", error);
    });
  },
  // 恢复数据
  restoreRow(row) {
    // 调用后端接口恢复数据
    restoreData(row).then(response => {
      if (response.code === 200) {
        // 数据恢复成功后，刷新历史记录列表
        //this.fetchHistoryList();
        this.historyOpen = false;
        this.getList();
        this.$message.success('数据还原成功');
      } else {
        this.$message.error('数据还原失败');
      }
    }).catch(error => {
      console.error('数据还原失败', error);
      this.$message.error('还原失败');
    });
  },
   // 处理 MD5 码
   handleMd5Success(md5) {
    //console.log('MD5 码：', md5);
      this.form.md5Hash = md5; // 将 MD5 码赋值给 md5Hash
    },
    //校验图片
    checkImage(row){
      checkImage(row).then(response => {
        if (response.code === 200) {
          this.$message.success('图片校验成功');
        } else {
          this.$message.error('图片被修改');
        }
      }).catch(error => {
        console.error('图片校验失败', error);
        this.$message.error('图片校验失败');
      });
    }
}
};
</script>
